package org.hxzon.demo.juntai.csserver.server;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.hxzon.demo.juntai.csserver.common.Config;
import org.hxzon.project.AppRuntimeException;

public class MyServer {

    private int port;
    private Executor executor;

    public MyServer(int port, Executor executor) {
        this.port = port;
        this.executor = executor;
    }

    public void start() {
        try {
            Selector selector = Selector.open();

            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.socket().bind(new InetSocketAddress(port));
            ssc.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {

                int readyCount = selector.select(Config.timeout_select);
                if (readyCount == 0) {
                    continue;
                }
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    if (key.isValid()) {
                        handle(key);
                    }
                    iter.remove();
                }
            }
        } catch (Exception e) {
            //throw AppRuntimeException.rethrow(e);
            Util.println(e);
        }

    }

    private void handle(SelectionKey key) {
        if (key.isAcceptable()) {
            ServerSocketChannel channel = (ServerSocketChannel) key.channel();
            try {
                SocketChannel sc = channel.accept();
                Util.registerChannel(key.selector(), sc, SelectionKey.OP_READ, new MyServerHandler(executor));//注册读事件  
            } catch (Exception e) {
                throw AppRuntimeException.rethrow(e);
            }
        }
        if (key.isReadable() || key.isWritable()) {
            MyServerHandler handler = (MyServerHandler) key.attachment();
            handler.handle(key);
        }
    }

    public void stop() {

    }

    public static void main(String[] args) {
        Executor executor = Executors.newCachedThreadPool();
        MyServer server = new MyServer(Config.port, executor);
        server.start();
    }
}
